﻿using System.Web.Mvc;
using Orchard;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.UI.Notify;
using Orchard.Security;
using LinqToTwitter;
using NGM.OpenAuthentication.Core.OAuth;
using Hazdesign.TwitterRules.Models;

namespace Hazdesign.TwitterRules.Services{
    public class TwitterService : ITwitterService {
        private readonly IOAuthProviderTwitterAuthorizer _twitterProvider;
        private readonly IOrchardServices _orchardServices;
        public TwitterService(IOAuthProviderTwitterAuthorizer twitterProvider, IOrchardServices orchardServices){
            this._twitterProvider = twitterProvider;
            this._orchardServices = orchardServices;
            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }
        public ILogger Logger { get; set; }

        public Message GetMessage(IUser user, string message){
            return new Tweet(user, message);
        }

        public bool Publish(Message message){
            var twitterAuthorizer = this._twitterProvider.GetAuthorizer(message.User);
            // can be null if there is no Twitter account associated.
            if (twitterAuthorizer == null) {
                var urlHelper = new UrlHelper(this._orchardServices.WorkContext.HttpContext.Request.RequestContext);
                var url = urlHelper.Action("Index", "Admin", new { Area = "NGM.OpenAuthentication" });
                this._orchardServices.Notifier.Add(NotifyType.Warning, T("The tweet '{0}' was not published, only users with an active Twitter account associated can publish tweets. The <a href=\"{1}\">Twitter account</a> needs to be configured.", message.PublishMessage, url));
                return false;
            }

            try {
                var twitterCtx = new TwitterContext(twitterAuthorizer);
                twitterCtx.UpdateStatus(message.PublishMessage);
            } catch(TwitterQueryException exception) { // TODO: HACK ****
                var errorMessage = T("There was an error while trying to publish the tweet: '{0}'.", message.PublishMessage);
                Logger.Error(exception, errorMessage.ToString());
                return false;
            }
            return true;
        }
    }
}